package com.yonyou.pmclouds.workstartreport.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.yonyou.pmclouds.ApplicationConsts;
import com.yonyou.pmclouds.basecom.billstatus.BillStatusConst;
import com.yonyou.pmclouds.basecom.consts.BillTypeConst;
import com.yonyou.pmclouds.basecom.consts.CheckItemConst;
import com.yonyou.pmclouds.basecom.entity.PageObject;
import com.yonyou.pmclouds.basecom.exception.BusinessException;
import com.yonyou.pmclouds.basecom.util.SqlUtil;
import com.yonyou.pmclouds.inspectitem.entity.InspectItemBillStatusConst;
import com.yonyou.pmclouds.picture.rmiitf.PictureRemoteService;
import com.yonyou.pmclouds.pmpub.entity.QueryListParam;
import com.yonyou.pmclouds.pmpub.rmiitf.IPageQuerySerivce;
import com.yonyou.pmclouds.project.entity.ProjectVO;
import com.yonyou.pmclouds.workquality.entity.WorkqualityDetailVO;
import com.yonyou.pmclouds.workquality.entity.WorkqualityVO;
import com.yonyou.pmclouds.workstartreport.entity.WorkStartCheckVO;
import com.yonyou.pmclouds.workstartreport.entity.WorkStartVO;
import com.yonyou.pmclouds.workstartreport.mapper.WorkStartCheckMapper;
import com.yonyou.pmclouds.workstartreport.mapper.WorkStartMapper;
import com.yonyou.pmclouds.workstartreport.mapper.WorkStartOtherMapper;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.*;

@Service(version = ApplicationConsts.APPLICATION_VERSION, interfaceClass = com.yonyou.pmclouds.workstartreport.rmiitf.WorkStartQuery.class)
public class WorkStartQueryImpl implements com.yonyou.pmclouds.workstartreport.rmiitf.WorkStartQuery , IPageQuerySerivce<WorkStartVO> {
    @Autowired
    private WorkStartMapper workStartMapper;
    @Autowired
    private WorkStartCheckMapper checkMapper;
    @Autowired
    private WorkStartOtherMapper otherMapper;
    @Autowired
    private PictureRemoteService picService;

    @Override
    public WorkStartVO[] getAllCondition(String id) {
        //根据项目ID查询所在项目下的所有开工报告单据
        WorkStartVO[] workStartVOS = workStartMapper.selectAllCondition(id);
        //这个时候单据内容主要存的都是主键，需要进行一些主键和名称之间的转换
        //根据项目ID获取项目对象
        ProjectVO projectVO = workStartMapper.selectProject(id);
        for (WorkStartVO w : workStartVOS) {
            //赋值项目名以及项目编号
            w.setProjectName(projectVO.getSname());
            w.setProjectCode(projectVO.getScode());
            //获取条件主键
            String pkWorkquality = w.getPkWorkquality();
            //获取开工条件对象
            WorkqualityVO workqualityVO = workStartMapper.selectWorkquality(pkWorkquality);
            //赋值条件名
            w.setConditionName(workqualityVO.getCheckname());
        }
        try {
            //为其展示添加不合格的照片
            getPictures(workStartVOS);
        } catch (BusinessException e) {
            e.printStackTrace();
        }
        return workStartVOS;

    }

    @Override
    public WorkStartVO[] getAllBill(String projectId) {
        WorkStartVO[] workStartVOS = workStartMapper.selectAllCondition(projectId);
        return workStartVOS;
    }

    /**
     * 添加不合格的检查项中的照片，最多9张
     */
    private void getPictures(WorkStartVO[] vos) throws BusinessException {
        //创建一个存放单据主键的集合
        Set<String> pkBills = new HashSet<>();
        //遍历单据对象数组
        for (WorkStartVO vo : vos) {
            if (vo != null && vo.getPkWorkstartreport() != null) {
                //添加单据主键
                pkBills.add(vo.getPkWorkstartreport());
            }
        }
        if (pkBills.size() == 0) return;
        //查询出所有单据下的检查项
        WorkStartCheckVO[] wv = checkMapper.selectByBills(SqlUtil.getSqlIn(pkBills.toArray(new String[pkBills.size()])));
        //记录不合格的检查项主键对应的单据主键
        Map<String, String> recordParent = new HashMap<>();
        if (ArrayUtils.isEmpty(wv)) return;
        //清空集合
        pkBills.clear();
        //取不合格的检查项
        for (WorkStartCheckVO vo : wv) {
            if (vo != null && vo.getQualification() == InspectItemBillStatusConst.BILLSTATUS_NO_PASS && vo.getPkCheck() != null) {
                //存入不合格的检查项主键
                pkBills.add(vo.getPkCheck());
                //存入不合格的检查项主键以及对应的单据主键
                recordParent.put(vo.getPkCheck(), vo.getPkWorkstartreport());
            }
        }
        //若检查项全部合格，则返回
        if (pkBills.size() == 0) return;
        //集合转数组，根据检查项ID查出来的Map集合中key对应的是检查项ID，value对应的是图片名称的集合
        Map<String, List<String>> picMap = picService.queryPicsByPkEntitys(pkBills.toArray(new String[pkBills.size()]));
        if (picMap.size() == 0) return;
        //该集合key对应单据ID，value对应的图片名称集合，最多只允许展示九张照片
        Map<String, List<String>> parentPicMap = new HashMap<>();
        //根据key遍历Map集合
        for (String key : picMap.keySet()) {
            //检查项主键对应的单据(开工报告)主键
            String pkParent = recordParent.get(key);
            if (pkParent != null) {
                if (parentPicMap.get(pkParent) == null) {
                    parentPicMap.put(pkParent, new ArrayList<String>());
                }
                //最多取9张照片
                if (parentPicMap.get(pkParent).size() < 9) {
                    int need = 9 - parentPicMap.get(pkParent).size();
                    for (int i = 0; i < Math.min(need, picMap.get(key).size()); i++) {
                        parentPicMap.get(pkParent).add(picMap.get(key).get(i));
                    }
                }
            }
        }
        for (WorkStartVO vo : vos) {
            List<String> pictureList = parentPicMap.get(vo.getPkWorkstartreport());
            if (pictureList == null) {
                continue;
            }
            //为单据展示对象的pictures属性赋值
            vo.setPictures(pictureList.toArray(new String[]{}));
        }
    }

    @Override
    public Integer counts() {
        Integer counts = workStartMapper.counts();
        return counts;
    }

    @Override
    public WorkStartVO getReport(String reportId) {
        //根据单据ID查询出单据信息
        WorkStartVO workStartVO = workStartMapper.selectReport(reportId);
        //获取条件主键
        String pkWorkquality = workStartVO.getPkWorkquality();
        //判断单据状态
        if (workStartVO.getBillstatus() != null) {
            switch (workStartVO.getBillstatus()) {
                case BillStatusConst.COMMON_APPROVING_STATUS:
                    workStartVO.setStatus("审批中");
                    break;
                case BillStatusConst.COMMON_REJECT_STATUS:
                    workStartVO.setStatus("驳回");
                    break;
                case BillStatusConst.COMMON_APPROVED_STATUS:
                    workStartVO.setStatus("审批通过");
                    break;
                case BillStatusConst.COMMON_COMMIT_STATUS:
                    workStartVO.setStatus("驳回后再提交");
                    break;
                case BillStatusConst.COMMON_FREE_STATUS:
                    workStartVO.setStatus("自由态");
            }
        }
        //根据条件主键以及单据主键获取所有检查项
        WorkStartCheckVO[] workStartCheckVOS = checkMapper.selectAllCheck(pkWorkquality, reportId);
        //构建检查项Id数组补全检查项信息，例如名称，描述，以及是否需要图片标识等。目的减少访问数据库次数。
        String[] checkItems = new String[workStartCheckVOS.length];
        for (int i = 0; i < workStartCheckVOS.length; i++) {
            checkItems[i] = workStartCheckVOS[i].getPkWorkqualitydetail();
        }
        WorkqualityDetailVO[] workqualityDetailVOS = workStartMapper.selectCheckItem(checkItems);
        //遍历补全检查项信息
        for (int i = 0; i < workStartCheckVOS.length; i++) {
            for (int j = 0; j < workqualityDetailVOS.length; j++) {
                if (workStartCheckVOS[i].getPkWorkqualitydetail().equals(workqualityDetailVOS[j].getPkWorkqualitydetail())) {
                    workStartCheckVOS[i].setCheckName(workqualityDetailVOS[j].getCheckitem());
                    workStartCheckVOS[i].setDescription(workqualityDetailVOS[j].getCheckdescription());
                    workStartCheckVOS[i].setNeedPhoto(workqualityDetailVOS[j].getNeedphoto());
                }
            }
            //查询图片 打印模板时会用到
            if (workStartCheckVOS[i].getLogo() == CheckItemConst.LOGO_ALL_PROSSESS) {
                String[] pictures = picService.queryPicNamesByPkEntity(workStartCheckVOS[i].getPkCheck());
                workStartCheckVOS[i].setPictures(pictures);
            }
            //是否具备资格中文转换
            switch (workStartCheckVOS[i].getQualification()) {
                case CheckItemConst.QUALIFICATION_HAVE:
                    workStartCheckVOS[i].setQualificationName("具备");
                    break;
                case CheckItemConst.QUALIFICATION_NO_HAVE:
                    workStartCheckVOS[i].setQualificationName("不具备");
                    break;
                case CheckItemConst.QUALIFICATION_NO_APPLICABLE:
                    workStartCheckVOS[i].setQualificationName("不适用");
            }
        }
            //为主实体的子实体的数组赋值，以便一起返回数据
            workStartVO.setWorkStartCheckVOS(workStartCheckVOS);
            //根据条件主键获取条件详细信息
            WorkqualityVO workqualityVO = workStartMapper.selectWorkquality(pkWorkquality);
            workStartVO.setConditionName(workqualityVO.getCheckname());
            //根据项目Id获取项目名以及项目编号
            String pkProject = workStartVO.getPkProject();
            ProjectVO projectVO = workStartMapper.selectProject(pkProject);
            workStartVO.setProjectName(projectVO.getSname());
            workStartVO.setProjectCode(projectVO.getScode());

            return workStartVO;

    }


    @Override
    public WorkStartCheckVO getCheck(String checkId) {
        WorkStartCheckVO workStartCheckVO = checkMapper.selectCheck(checkId);
        //获取检查项的名称
        String s = workStartMapper.selectName(checkId);
        workStartCheckVO.setCheckName(s);
        //查询检查项ID对应的图片
        String[] pictures = picService.queryPicNamesByPkEntity(workStartCheckVO.getPkCheck());
        workStartCheckVO.setPictures(pictures);
        return workStartCheckVO;

    }

    @Override
    public WorkqualityDetailVO[] getAllCheck(String conditionId) {
        WorkqualityDetailVO[] workqualityDetailVOS = workStartMapper.selectQualityDetatil(conditionId);
        return workqualityDetailVOS;

    }

    @Override
    public WorkqualityVO[] getReportCondition(String pkTenant) {
        //查询该租户下的所有开工条件
        WorkqualityVO[] workqualityVO = otherMapper.selectAllCondition(pkTenant);
        return workqualityVO;
    }

    @Override
    public ProjectVO[] getProject(String status) {
        ProjectVO[] projectVOS = otherMapper.selectProject(status);
        return projectVOS;
    }

    @Override
    public ProjectVO getProjectById(String projectId) {
        ProjectVO projectVO = workStartMapper.selectProject(projectId);
        return projectVO;
    }

    @Override
    public PageObject<Object> queryByCondition(String[] pkProject, String[] creators, String startDate, String endDate, int[] billStatus, int start, int size) throws BusinessException {

        int count = workStartMapper.countByCondition(pkProject, creators, startDate, endDate, billStatus);
        WorkStartVO[] workStartVOS = workStartMapper.queryByCondition(pkProject, creators, startDate, endDate, billStatus, start, size);
        for (WorkStartVO w : workStartVOS) {
            //获取项目主键
            String pk = w.getPkProject();
            ProjectVO projectVO = workStartMapper.selectProject(pk);
            //赋值项目名
            w.setProjectName(projectVO.getSname());
            //获取查询条件总数
            String pkTenant = w.getPkTenant();
            if (pkTenant != null) {
                Integer workqualityCount = workStartMapper.selectWorkqualityCount(pkTenant);
                w.setWorkqualityCount(workqualityCount);
            }
            //获取不具备检查项数量
            Integer checkCount = checkMapper.selectCount(w.getPkWorkstartreport(), w.getPkTenant());
            w.setCheckCount(checkCount);
        }
        return new PageObject<Object>(workStartVOS, count, start);
    }

    @Override
    public int countByProject(QueryListParam param) throws BusinessException{

        int count = workStartMapper.countByCondition( new String[]{param.getPkProject()}, null,  param.getStartDate(), param.getEndDate(), null);

        return count;
    }

    @Override
    public WorkStartVO[] queryByProject(QueryListParam param) throws BusinessException {
        WorkStartVO[] vos = workStartMapper.queryByCondition(new String[]{param.getPkProject()}, null,  param.getStartDate(), param.getEndDate(), null,param.getPageStart(),param.getPageSize());
        getPictures(vos);

        return vos;
    }

    @Override
    public String getBillType() {
        return BillTypeConst.WORKSTART_BILLTYPE;
    }
}